﻿using DevExpress.XtraGrid.Views.BandedGrid;
using DLL;
using NursingFormSystem.BLL;
using NursingFormSystem.Common;
using NursingFormSystem.Model;
using NursingFormSystem.NursingEntry;
using SQLDLL;
using System;
using System.Data;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace NursingFormSystem.NursingRecordSheet
{
    public partial class HistorySheet : Form
    {
        #region 变量声明
        NursingFormSystem.NurFormsService.NursingForm formService = new NursingFormSystem.NurFormsService.NursingForm();
        PatientInfo PatientInfo;
        Tb_User LoginUser;
        DataTable IOData;
        bool continueflag;
        int continuenum = 0;
        #endregion

        #region 窗体函数
        public HistorySheet(Tb_User loginUser, PatientInfo patientInfo)
        {
            InitializeComponent();
            ccb_printType.SelectedIndex = 1;//默认打印全部科室护理记录点
            LoginUser = loginUser;
            this.PatientInfo = patientInfo;
            continueflag = false;
            BindControl();
            LoadData("", "");
        }
        #endregion

        #region 共用查询方法
        private void LoadData(string StatDate, string EndDate)
        {
            string patientid = PatientInfo.PATIENT_ID;//住院号
            int VisitId = PatientInfo.VISIT_ID;//住院次数
            int FormId = (int)FormType.NurseForm;//10003  //表单ID
            string select_sql = "";
            select_sql += @"SELECT  * ,                                   
                                '' AS riqi,
                                '' AS shijian,
                                '' AS tiwen,
                                '' AS maibo,
                                '' AS xinlv,
                                '' AS huxi,
                                '' AS xueya,
                                '' AS spo2,
                                '' AS fanshen,
                                '' AS shenzhi,
                                '' AS tongkongdaxiaozuo,
                                '' AS tongkongdaxiaoyou,
                                '' AS tongkongduiguangzuo,
                                '' AS tongkongduiguangyou,
                                '' AS shuruyetimingcheng,
                                '' AS shuruyetiliang,
                                '' AS shuruyetitujing,
                                '' AS paichuliutiliangmingcheng,
                                '' AS paichuliutiliangliang,
                                '' AS bingqingzhiliaojihulicuoshi,
                                '' AS qianming,
                                '' AS newpageflag,
                                AreaId AS Area, 
                                    SUBSTRING(' ', 1, 10) AS RiQi 
                            FROM    dbo.NursingFormRecord 
                            WHERE   FormId = {0} ";
            if (ccb_printType.SelectedItem == "本科室")
            {
                select_sql += " and AreaId='" + LoginUser.DepartmentCode + "' ";
            }
            select_sql += @"AND patientid = '{1}' AND VisitId = {2} {3} ORDER BY [AssessmentDate] DESC";
            string whereList = string.Empty;
            if (StatDate != "" && EndDate != "")
            {
                StatDate += " 00:00:00";
                EndDate += " 00:00:00";
                whereList = string.Format(" AND [AssessmentDate]>=CONVERT(DATETIME,'{0}') AND  [AssessmentDate]<CONVERT(DATETIME,'{1}')", StatDate, Convert.ToDateTime(EndDate).AddDays(1).ToString("yyyy-MM-dd HH:mm:ss"));
            }
            select_sql = string.Format(select_sql, FormId, patientid, VisitId, whereList);
            DataTable dt = (SqlHelper.ExecuteDataset(select_sql, CommandType.Text)).Tables[0];
            DataTable dtt = new DataTable();

            dtt.Columns.Add("riqi", typeof(string));//日期
            dtt.Columns.Add("shijian", typeof(string));//时间
            dtt.Columns.Add("tiwen", typeof(string));//体温
            dtt.Columns.Add("maibo", typeof(string));//脉搏
            dtt.Columns.Add("xinlv", typeof(string));//心率
            dtt.Columns.Add("huxi", typeof(string));//呼吸
            dtt.Columns.Add("xueya", typeof(string));//血压
            dtt.Columns.Add("spo2", typeof(string));//血氧饱和度
            dtt.Columns.Add("fanshen", typeof(string));//翻身
            dtt.Columns.Add("shenzhi", typeof(string));//神志
            dtt.Columns.Add("tongkongdaxiaozuo", typeof(string));//瞳孔大小左
            dtt.Columns.Add("tongkongdaxiaoyou", typeof(string));//瞳孔大小右
            dtt.Columns.Add("tongkongduiguangzuo", typeof(string));//对光反射左
            dtt.Columns.Add("tongkongduiguangyou", typeof(string));//对光反射右
            dtt.Columns.Add("shuruyetimingcheng", typeof(string));//输入名称
            dtt.Columns.Add("shuruyetiliang", typeof(string));//输入量
            dtt.Columns.Add("shuruyetitujing", typeof(string));//途径
            dtt.Columns.Add("paichuliutiliangmingcheng", typeof(string));//排除名称
            dtt.Columns.Add("paichuliutiliangliang", typeof(string));//排除量
            dtt.Columns.Add("bingqingzhiliaojihulicuoshi", typeof(string));//病情及护理措施
            dtt.Columns.Add("qianming", typeof(string));//签名
            dtt.Columns.Add("Id", typeof(string));//ID用来指示哪一条 
            dtt.Columns.Add("Area", typeof(string));
            dtt.Columns.Add("SumInValue", typeof(string)); //本次总入量
            dtt.Columns.Add("SumOutValue", typeof(string));//本次总出量
            dtt.Columns.Add("SumFlag12", typeof(string));//具有统计12小时的标识，为后续合并设置提供标识
            dtt.Columns.Add("SumFlag24", typeof(string));//具有统计124小时的标识，为后续合并设置提供标识

            if (dt.Rows.Count <= 0)
            {
                gridControl1.DataSource = dt;
                return;
            }
            foreach (DataRow dr in dt.Rows)
            {
                string suminvalue = "";
                string sumoutvalue = "";
                var NursingFormData = Convert.ToString(dr["NursingFormData"]);
                ClinicalCare fd = new ClinicalCare();
                fd = XmlUtil.XMLToObject<ClinicalCare>(NursingFormData, Encoding.UTF8);
                float tempinput = 0;
                if (fd.ShuRuYeTiLiang.Contains(","))
                {
                    string[] str = fd.ShuRuYeTiLiang.Split(',');
                    for (int j = 0; j < str.Length; j++)
                    {
                        if (RegexHelper.IsFloat(str[j]))
                        {
                            tempinput = tempinput + Convert.ToSingle(str[j]);
                        }
                    }
                    suminvalue = Convert.ToString(tempinput);
                }
                else
                {
                    suminvalue = fd.ShuRuYeTiLiang;
                }
                float tempout = 0;
                if (fd.PaiChuYeLiangLiang.Contains(","))
                {
                    string[] str = fd.PaiChuYeLiangLiang.Split(',');
                    for (int j = 0; j < str.Length; j++)
                    {
                        if (RegexHelper.IsFloat(str[j]))
                        {
                            tempout = tempout + Convert.ToSingle(str[j]);
                        }
                    }
                    sumoutvalue = Convert.ToString(tempout);
                }
                else
                {
                    sumoutvalue = fd.PaiChuYeLiangLiang;
                }
                DataRow row = dtt.NewRow();
                row["riqi"] = fd.RiQi;//日期
                row["shijian"] = fd.ShiJian;//时间
                row["tiwen"] = fd.TiWen;//体温
                row["maibo"] = fd.MaiBo;//脉搏
                row["xinlv"] = fd.XinLv;//心率
                row["huxi"] = fd.HuXi;//呼吸
                row["xueya"] = fd.XueYa.Equals("/") ? string.Empty : fd.XueYa;//血压
                row["spo2"] = fd.Spo;//血氧饱和度
                row["fanshen"] = fd.FanShen == "1" ? "√" : "";//翻身
                row["shenzhi"] = fd.ShenZhi;//神志
                row["tongkongdaxiaozuo"] = fd.TongKongDaXiaoZuo;//瞳孔大小左
                row["tongkongdaxiaoyou"] = fd.TongKongDaXiaoYou;//瞳孔大小右
                row["tongkongduiguangzuo"] = fd.TongKongDuiGuangZuo;//对光反射左
                row["tongkongduiguangyou"] = fd.TongKongDuiGuangYou;//对光反射右
                row["shuruyetimingcheng"] = fd.ShuRuYeTiMingCheng.Replace(",", "\n");//输入名称
                row["shuruyetiliang"] = fd.ShuRuYeTiLiang.Replace(",", "\n");//输入量
                row["shuruyetitujing"] = fd.ShuRuYeTiTuJing.Replace(",", "\n");//途径
                row["paichuliutiliangmingcheng"] = fd.PaiChuYeLiangMingCheng.Replace(",", "\n");//排除名称
                row["paichuliutiliangliang"] = fd.PaiChuYeLiangLiang.Replace(",", "\n");//排除量
                row["bingqingzhiliaojihulicuoshi"] = fd.BingQingZhiLiaoJiHuLiCuoShi;//病情及护理措施
                row["qianming"] = fd.QianMing;//签名
                row["Id"] = dr["ID"];//ID用来指示哪一条 
                row["Area"] = dr["AreaId"] + "";
                row["SumInValue"] = suminvalue; //本次总入量
                row["SumOutValue"] = sumoutvalue;//本次总出量
                row["SumFlag12"] = string.Empty;//具有统计12小时的标识，为后续合并设置提供标识
                row["SumFlag24"] = string.Empty;//具有统计24小时的标识，为后续合并设置提供标识
                dtt.Rows.Add(row);
            }

            #region 获得出入量统计的部分，然后加以添加相关行
            dtt.DefaultView.Sort = "riqi asc,shijian asc";
            dtt = dtt.DefaultView.ToTable();
            GetSumIO();
            DataTable tempdt = dtt.Clone();
            if (IOData.Rows.Count > 0)
            {
                for (int j = 0; j < IOData.Rows.Count; j++)
                {
                    if (IOData.Rows[j]["Group12"].ToString().Contains("Y")) //是否有12小时的统计标识
                    {
                        float invalue = 0f;
                        float outvalue = 0f;
                        for (int m = 0; m < dtt.Rows.Count; m++)
                        {
                            if (Convert.ToDateTime(IOData.Rows[j]["SumDate"]).ToString("yyyy-MM-dd").Contains(Convert.ToDateTime(dtt.Rows[m]["riqi"]).ToString("yyyy-MM-dd")))//同一天日期
                            {
                                string _strtime1 = "07:01";
                                string _strtime2 = "19:00";
                                TimeSpan dsptime1 = DateTime.Parse(_strtime1).TimeOfDay;
                                TimeSpan dsptime2 = DateTime.Parse(_strtime2).TimeOfDay;
                                TimeSpan dspnow = DateTime.Parse(dtt.Rows[m]["shijian"].ToString()).TimeOfDay;
                                if ((dspnow >= dsptime1) && (dspnow <= dsptime2))
                                {
                                    if (RegexHelper.IsFloat(dtt.Rows[m]["SumInValue"]))
                                    {
                                        invalue = invalue + Convert.ToSingle(dtt.Rows[m]["SumInValue"].ToString());
                                    }
                                    if (RegexHelper.IsFloat(dtt.Rows[m]["SumOutValue"]))
                                    {
                                        outvalue = outvalue + Convert.ToSingle(dtt.Rows[m]["SumOutValue"].ToString());
                                    }
                                }
                            }
                        }
                        string suminvalue = Convert.ToString(invalue);
                        string sumoutvalue = Convert.ToString(outvalue);
                        DateTime tempdt12 = Convert.ToDateTime(IOData.Rows[j]["SumDate"]);
                        string date12 = tempdt12.ToString("yyyy-MM-dd");

                        DataRow row = tempdt.NewRow();
                        row["riqi"] = date12;//日期
                        row["shijian"] = "19:01";//时间
                        row["tiwen"] = suminvalue;//体温
                        row["maibo"] = "12小时总出量:";//脉搏
                        row["xinlv"] = sumoutvalue;//心率
                        row["huxi"] = "";//呼吸
                        row["xueya"] = "";//血压
                        row["spo2"] = "";//血氧饱和度
                        row["fanshen"] = "";//翻身
                        row["shenzhi"] = "";//神志
                        row["tongkongdaxiaozuo"] = "";//瞳孔大小左
                        row["tongkongdaxiaoyou"] = "";//瞳孔大小右
                        row["tongkongduiguangzuo"] = "";//对光反射左
                        row["tongkongduiguangyou"] = "";//对光反射右
                        row["shuruyetimingcheng"] = "";//输入名称
                        row["shuruyetiliang"] = "";//输入量
                        row["shuruyetitujing"] = "";//途径
                        row["paichuliutiliangmingcheng"] = "";//排除名称
                        row["paichuliutiliangliang"] = "";//排除量
                        row["bingqingzhiliaojihulicuoshi"] = "统计范围:" + date12 + " 07:01至" + date12 + " 19:00";//病情及护理措施
                        row["qianming"] = "";//签名
                        row["Id"] = Convert.ToDateTime(IOData.Rows[j]["SumDate"]).ToString("yyyy-MM-dd 07:00:00.012");//ID
                        row["Area"] = "12小时总入量:";
                        row["SumInValue"] = suminvalue; //本次总入量
                        row["SumOutValue"] = sumoutvalue;//本次总出量
                        row["SumFlag12"] = "Y";//具有统计12小时的标识，为后续合并设置提供标识
                        row["SumFlag24"] = string.Empty;//具有统计24小时的标识，为后续合并设置提供标识
                        tempdt.Rows.Add(row);
                    }

                    if (IOData.Rows[j]["Group24"].ToString().Contains("Y")) //是否有24小时的统计标识
                    {
                        float invalue = 0f;
                        float outvalue = 0f;
                        string valueof24_1 = "1980-01-01";
                        for (int m = 0; m < dt.Rows.Count; m++)
                        {
                            if (valueof24_1.Contains(dtt.Rows[m]["riqi"].ToString()))
                            {
                                string _strtime1 = "07:00";
                                TimeSpan dsptime1 = DateTime.Parse(_strtime1).TimeOfDay;
                                TimeSpan dspnow = DateTime.Parse(dtt.Rows[m]["shijian"].ToString()).TimeOfDay;
                                if (dspnow <= dsptime1)
                                {
                                    if (RegexHelper.IsFloat(dtt.Rows[m]["SumInValue"]))
                                    {
                                        invalue = invalue + Convert.ToSingle(dtt.Rows[m]["SumInValue"]);
                                    }
                                    if (RegexHelper.IsFloat(dtt.Rows[m]["SumOutValue"]))
                                    {
                                        outvalue = outvalue + Convert.ToSingle(dtt.Rows[m]["SumOutValue"]);
                                    }
                                }
                            }
                            else if (Convert.ToDateTime(IOData.Rows[j]["SumDate"]).ToString("yyyy-MM-dd").Contains(Convert.ToDateTime(dtt.Rows[m]["riqi"]).ToString("yyyy-MM-dd")))//同一天日期
                            {
                                string _strtime1 = "07:01";
                                TimeSpan dsptime1 = DateTime.Parse(_strtime1).TimeOfDay;
                                TimeSpan dspnow = DateTime.Parse(dtt.Rows[m]["shijian"].ToString()).TimeOfDay;
                                if (dspnow >= dsptime1)
                                {
                                    if (RegexHelper.IsFloat(dtt.Rows[m]["SumInValue"]))
                                    {
                                        invalue = invalue + Convert.ToSingle(dtt.Rows[m]["SumInValue"]);
                                    }
                                    if (RegexHelper.IsFloat(dtt.Rows[m]["SumOutValue"].ToString()))
                                    {
                                        outvalue = outvalue + Convert.ToSingle(dtt.Rows[m]["SumOutValue"]);
                                    }
                                }
                                DateTime tempdt01 = Convert.ToDateTime(dtt.Rows[m]["riqi"].ToString());
                                valueof24_1 = tempdt01.AddDays(1).ToString("yyyy-MM-dd");
                            }
                        }
                        string suminvalue = Convert.ToString(invalue);
                        string sumoutvalue = Convert.ToString(outvalue);
                        string date = Convert.ToDateTime(IOData.Rows[j]["SumDate"]).ToString("yyyy-MM-dd");
                        string date24 = Convert.ToDateTime(IOData.Rows[j]["SumDate"]).AddDays(1).ToString("yyyy-MM-dd");

                        DataRow row = tempdt.NewRow();
                        row["riqi"] = date24;//日期
                        row["shijian"] = "07:01";//时间
                        row["tiwen"] = suminvalue;//体温
                        row["maibo"] = "24小时总出量:";//脉搏
                        row["xinlv"] = sumoutvalue;//心率
                        row["huxi"] = "";//呼吸
                        row["xueya"] = "";//血压
                        row["spo2"] = "";//血氧饱和度
                        row["fanshen"] = "";//翻身
                        row["shenzhi"] = "";//神志
                        row["tongkongdaxiaozuo"] = "";//瞳孔大小左
                        row["tongkongdaxiaoyou"] = "";//瞳孔大小右
                        row["tongkongduiguangzuo"] = "";//对光反射左
                        row["tongkongduiguangyou"] = "";//对光反射右
                        row["shuruyetimingcheng"] = "";//输入名称
                        row["shuruyetiliang"] = "";//输入量
                        row["shuruyetitujing"] = "";//途径
                        row["paichuliutiliangmingcheng"] = "";//排除名称
                        row["paichuliutiliangliang"] = "";//排除量
                        row["bingqingzhiliaojihulicuoshi"] = "统计范围:" + date + " 07:01至" + date24 + " 07:00";//病情及护理措施
                        row["qianming"] = "";//签名
                        row["Id"] = Convert.ToDateTime(IOData.Rows[j]["SumDate"]).ToString("yyyy-MM-dd 07:00:00.024");//ID
                        row["Area"] = "24小时总入量:";
                        row["SumInValue"] = suminvalue; //本次总入量
                        row["SumOutValue"] = sumoutvalue;//本次总出量
                        row["SumFlag12"] = string.Empty;//具有统计12小时的标识，为后续合并设置提供标识
                        row["SumFlag24"] = "Y";//具有统计124小时的标识，为后续合并设置提供标识
                        tempdt.Rows.Add(row);
                    }

                    #region 对自定义统计进行逻辑计算
                    object groupDiy = IOData.Rows[j]["GroupDiy"];
                    object beginTime = IOData.Rows[j]["BeginTime"];
                    object sumDate = IOData.Rows[j]["SumDate"];
                    if (groupDiy != DBNull.Value && groupDiy != null && Convert.ToInt32(groupDiy) > 0) //是否有自定义的统计标识
                    {
                        float invalue = 0f;
                        float outvalue = 0f;
                        string valueofDiyDate = "1980-01-01";
                        int maxHours = Convert.ToInt32(groupDiy);
                        string _strtime1 = beginTime.ToString();
                        if (string.IsNullOrEmpty(_strtime1)) _strtime1 = "07:01";

                        TimeSpan dsptime1 = DateTime.Parse(_strtime1).TimeOfDay;//统计起始时间
                        DateTime mintime = Convert.ToDateTime(sumDate).AddHours(dsptime1.Hours).AddMinutes(dsptime1.Minutes);//完整起始时间
                        DateTime maxtime = mintime.AddHours(maxHours);//完整结束时间
                        for (int m = 0; m < dtt.Rows.Count; m++)
                        {
                            string date = Convert.ToDateTime(dtt.Rows[m]["riqi"]).ToString("yyyy-MM-dd");//护理日期
                            TimeSpan dspnow = DateTime.Parse(dtt.Rows[m]["shijian"].ToString()).TimeOfDay;//护理时间
                            DateTime itemTime = Convert.ToDateTime(date).AddHours(dspnow.Hours).AddMinutes(dspnow.Minutes);
                            if (itemTime >= mintime && itemTime <= maxtime)
                            {
                                if (RegexHelper.IsFloat(dtt.Rows[m]["SumInValue"]))
                                {
                                    invalue = invalue + Convert.ToSingle(dtt.Rows[m]["SumInValue"]);
                                }
                                if (RegexHelper.IsFloat(dtt.Rows[m]["SumOutValue"]))
                                {
                                    outvalue = outvalue + Convert.ToSingle(dtt.Rows[m]["SumOutValue"]);
                                }
                            }
                            DateTime tempdt01 = Convert.ToDateTime(date);
                            valueofDiyDate = tempdt01.AddDays(1).ToString("yyyy-MM-dd");
                        }
                        string suminvalue = Convert.ToString(invalue);
                        string sumoutvalue = Convert.ToString(outvalue);
                        string dateDiy = Convert.ToDateTime(sumDate).ToString("yyyy-MM-dd");


                        DataRow row = tempdt.NewRow();
                        row["riqi"] = maxtime.ToString("yyyy-MM-dd");//日期
                        row["shijian"] = DateTimeHelper.HHmmssToHHmm(maxtime.AddMinutes(1).ToString("HH:mm"));//时间
                        row["tiwen"] = suminvalue;//体温
                        row["maibo"] = maxHours + "小时总出量:";//脉搏
                        row["xinlv"] = sumoutvalue;//心率
                        row["huxi"] = "";//呼吸
                        row["xueya"] = "";//血压
                        row["spo2"] = "";//血氧饱和度
                        row["fanshen"] = "";//翻身
                        row["shenzhi"] = "";//神志
                        row["tongkongdaxiaozuo"] = "";//瞳孔大小左
                        row["tongkongdaxiaoyou"] = "";//瞳孔大小右
                        row["tongkongduiguangzuo"] = "";//对光反射左
                        row["tongkongduiguangyou"] = "";//对光反射右
                        row["shuruyetimingcheng"] = "";//输入名称
                        row["shuruyetiliang"] = "";//输入量
                        row["shuruyetitujing"] = "";//途径
                        row["paichuliutiliangmingcheng"] = "";//排除名称
                        row["paichuliutiliangliang"] = "";//排除量
                        row["bingqingzhiliaojihulicuoshi"] = "统计范围:" + mintime.ToString("yyyy-MM-dd HH:mm:ss至") + maxtime.ToString("yyyy-MM-dd HH:mm:ss");//病情及护理措施
                        row["qianming"] = "";//签名
                        row["Id"] = Convert.ToDateTime(Convert.ToDateTime(sumDate).ToString("yyyy-MM-dd") + " " + beginTime).AddMilliseconds(Convert.ToInt32(groupDiy)).ToString("yyyy-MM-dd HH:mm:ss.fff");//ID                     
                        row["Area"] = maxHours + "小时总入量:";
                        row["SumInValue"] = ""; //本次总入量
                        row["SumOutValue"] = "";//本次总出量
                        row["SumFlag12"] = suminvalue;//具有统计12小时的标识，为后续合并设置提供标识
                        row["SumFlag24"] = sumoutvalue;//具有统计124小时的标识，为后续合并设置提供标识
                        tempdt.Rows.Add(row);
                    }
                    #endregion
                }
            }
            #endregion

            for (int n = 0; n < tempdt.Rows.Count; n++)
            {
                DataRow dr = dtt.NewRow();
                dr = tempdt.Rows[n];
                dtt.Rows.Add(dr.ItemArray);
            }
            dtt.DefaultView.Sort = "riqi desc,shijian desc ";
            dtt = dtt.DefaultView.ToTable();
            gridControl1.DataSource = dtt;
            bandedGridView1.TopRowIndex = topIndex;//解决dev GridControl刷新数据后，滚动条恢复原来位置
        }
        private void GetSumIO()
        {
            string sql = @"SELECT SumDate,Group12,Group24,GroupDiy,BeginTime FROM [BNNursingDocsSystem_Develop].[dbo].[NursingFormSumIO](NOLOCK) WHERE PatientId ='{0}' AND VisitId='{1}' AND FormId='{2}'";
            sql = string.Format(sql, PatientInfo.PATIENT_ID, PatientInfo.VISIT_ID, (int)FormType.NurseForm);
            IOData = new DataTable();
            IOData = SqlHelper.ExecuteDataset(sql, CommandType.Text).Tables[0];
        }
        #endregion

        #region 列名设置居中
        private void BindControl()
        {
            dateStart.DateTime = DateTime.Now.AddDays(-30).Date;
            dateEnd.DateTime = DateTime.Now;
            foreach (GridBand gridBand in this.bandedGridView1.Bands)//设置居中
            {
                foreach (GridBand gridBandSecond in gridBand.Children)
                {
                    gridBandSecond.OptionsBand.FixedWidth = true;
                    gridBandSecond.AppearanceHeader.Options.UseTextOptions = true;
                    gridBandSecond.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                    gridBandSecond.AppearanceHeader.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center;
                }
                gridBand.OptionsBand.FixedWidth = true;
                gridBand.AppearanceHeader.Options.UseTextOptions = true;
                gridBand.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                gridBand.AppearanceHeader.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center;
            }
        }
        #endregion

        #region 查询
        private void btnSearch_Click(object sender, EventArgs e)
        {
            string StatDate = this.dateStart.Text;
            string EndDate = this.dateEnd.Text;

            if (string.IsNullOrEmpty(StatDate) || string.IsNullOrEmpty(EndDate))
            {
                MessageBox.Show("查询日期不能为空！");
            }
            LoadData(StatDate, EndDate);
        }
        #endregion

        #region 新增
        private void btnAdd_Click(object sender, EventArgs e)
        {
            AddSheet addForm = new AddSheet(LoginUser, PatientInfo, string.Empty);
            addForm.ShowDialog();
            if (addForm.DialogResult == DialogResult.OK)
            {
                LoadData("", "");
            }
        }
        #endregion

        #region 修改
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            string Id = bandedGridView1.GetRowCellValue(bandedGridView1.FocusedRowHandle, "Id").ToString();
            if (!string.IsNullOrEmpty(Id) && Regex.IsMatch(Id, @"^\d+$"))
            {
                AddSheet addForm = new AddSheet(LoginUser, PatientInfo, Id);
                addForm.ShowDialog();
                if (addForm.DialogResult != DialogResult.OK) return;
                LoadData("", "");
                return;
            }
            if (!string.IsNullOrEmpty(Id) && Id.IndexOf("-") > 0 && Id.Split('-').Length == 3 && !Id.EndsWith("012") && !Id.EndsWith("024"))
            {
                //重新编辑自定义统计
                NursingSummaryHours frm = new NursingSummaryHours(Id);
                frm.ShowDialog();
                if (frm.DialogResult != DialogResult.OK) return;
                //return data:
                string date = frm.Date;
                string stime = frm.Stime;
                string etime = frm.Etime;
                TimeSpan _etime = DateTime.Parse(etime).TimeOfDay;
                TimeSpan _stime = DateTime.Parse(stime).TimeOfDay;
                int hours = (_etime.Hours - _stime.Hours);
                if (hours >= 0) hours += 1;
                if (hours < 0) hours = 24 + hours + 1;
                string sqldefault = @"if(EXISTS (SELECT Id FROM NursingFormSumIO(NOLOCK) WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}'  ))
                            BEGIN UPDATE NursingFormSumIO SET  GroupDiy ='{12}',BeginTime='{11}' WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}'  END ELSE BEGIN
                            INSERT INTO NursingFormSumIO (PatientId,VisitId,SumDate,PatientName,BedNo,DepartmentId,DepartmentName,AreaId,AreaName,FormId,FormName,Group12,Group24,BeginTime,GroupDiy)
                            VALUES('{0}','{1}','{2}' ,'{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}',NULL,NULL,'{11}','{12}') END";
                sqldefault = string.Format(sqldefault, PatientInfo.PATIENT_ID, PatientInfo.VISIT_ID, date, PatientInfo.PATIENT_NAME, PatientInfo.BED_NO, PatientInfo.DEPARTMENT_ID, PatientInfo.DEPARTMENT_NAME, PatientInfo.NURSE_CELL_CODE, PatientInfo.NURSE_CELL_NAME, (int)FormType.NurseForm, EnumHelper.GetDescription(FormType.NurseForm), stime, hours);
                SqlHelper.ExecuteNonQuery(sqldefault);
                LoadData(this.dateStart.Text, this.dateEnd.Text);
                MessageBox.Show("操作成功");
                return;
            }
        }
        #endregion

        #region 打印
        private void btnPrint_Click(object sender, EventArgs e)
        {
            //多张打印
            SheetPrints f = new SheetPrints(LoginUser, PatientInfo, dateStart.DateTime, dateEnd.DateTime, ccb_printType.SelectedItem + "", continueflag, continuenum);
            f.Show();
            continueflag = false;
        }
        #endregion

        #region 删除
        /// <summary>
        /// 根据id 返回 护理单
        /// </summary>
        /// <returns></returns>
        public DataRow GetNursingFormById(string id)
        {
            string sql = string.Format("SELECT TOP 1 * FROM dbo.NursingFormRecord(NOLOCK) WHERE Id='{0}'", id);
            DataSet ds = SqlHelper.ExecuteDataset(sql, CommandType.Text);
            if (ds == null || ds.Tables.Count <= 0 || ds.Tables[0].Rows.Count <= 0) return null;
            return ds.Tables[0].Rows[0];
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (bandedGridView1.DataRowCount <= 0) return;
            int num = bandedGridView1.GetSelectedRows()[0];
            string id = bandedGridView1.GetRowCellValue(bandedGridView1.FocusedRowHandle, "Id").ToString();
            if (!RegexHelper.IsInt32(id)) return;
            if (MessageBox.Show("确定要删除数据吗？", "删除前确认", MessageBoxButtons.OKCancel) != DialogResult.OK) return;
            var ret2 = formService.DeleteNursingFormRecord(id);
            MessageBox.Show(ret2.M);
            if (ret2.Code != 1) return;
            string dateStart = this.dateStart.Text;
            string dateEnd = this.dateEnd.Text;
            LoadData(dateStart, dateEnd);
            #region 上传海泰
            DataRow row = GetNursingFormById(id);
            if (row == null) return;
            var NursingFormData = Convert.ToString(row["NursingFormData"]);
            ClinicalCare fd = new ClinicalCare();
            fd = XmlUtil.XMLToObject<ClinicalCare>(NursingFormData, Encoding.UTF8);
            if (Base.ESSwitchHT == "1")
            {
                SynchroBLL synchro = new SynchroBLL();
                ClinicalNursinguser cn = new ClinicalNursinguser();
                cn.PatientId = bandedGridView1.GetRowCellValue(num, "PatientId").ToString();
                cn.PatientName = bandedGridView1.GetRowCellValue(num, "PatientName").ToString();
                cn.data = bandedGridView1.GetRowCellValue(num, "data").ToString();
                cn.Updatetime = System.DateTime.Now;
                cn.UpdateuserId = LoginUser.UserId;
                cn.UpdateuserName = LoginUser.UserName;
                cn.DepId = LoginUser.DepartmentCode;
                cn.DepName = LoginUser.DepartmentName;
                cn.syncSN = row["syncSN"] + "";
                synchro.clinicalNursingInfoAsyncToEMRDelegateMethod(cn, "001", "3");
            }
            #endregion
        }
        #endregion

        #region 双击事件查询
        private void bandedGridView1_DoubleClick(object sender, EventArgs e)
        {
            if (bandedGridView1.RowCount <= 0) return;
            string Id = bandedGridView1.GetRowCellValue(bandedGridView1.FocusedRowHandle, "Id").ToString();
            if (string.IsNullOrEmpty(Id)) return;
            if (Id.IndexOf("-") > 0 && Id.Split('-').Length == 3 && !Id.EndsWith("012") && !Id.EndsWith("024"))
            {
                //重新编辑自定义统计
                NursingSummaryHours frm = new NursingSummaryHours(Id);
                frm.ShowDialog();
                if (frm.DialogResult != DialogResult.OK) return;
                //return data:
                string date = frm.Date;
                string stime = frm.Stime;
                string etime = frm.Etime;
                TimeSpan _etime = DateTime.Parse(etime).TimeOfDay;
                TimeSpan _stime = DateTime.Parse(stime).TimeOfDay;
                int hours = (_etime.Hours - _stime.Hours);
                if (hours >= 0) hours += 1;
                if (hours < 0) hours = 24 + hours + 1;
                string sqldefault = @"if(EXISTS (SELECT Id FROM NursingFormSumIO(NOLOCK) WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}'  ))
                            BEGIN UPDATE NursingFormSumIO SET  GroupDiy ='{12}',BeginTime='{11}' WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}'  END ELSE BEGIN
                            INSERT INTO NursingFormSumIO (PatientId,VisitId,SumDate,PatientName,BedNo,DepartmentId,DepartmentName,AreaId,AreaName,FormId,FormName,Group12,Group24,BeginTime,GroupDiy)
                            VALUES('{0}','{1}','{2}' ,'{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}',NULL,NULL,'{11}','{12}') END";
                sqldefault = string.Format(sqldefault, PatientInfo.PATIENT_ID, PatientInfo.VISIT_ID, date, PatientInfo.PATIENT_NAME, PatientInfo.BED_NO, PatientInfo.DEPARTMENT_ID, PatientInfo.DEPARTMENT_NAME, PatientInfo.NURSE_CELL_CODE, PatientInfo.NURSE_CELL_NAME, (int)FormType.NurseForm, EnumHelper.GetDescription(FormType.NurseForm), stime, hours);
                SqlHelper.ExecuteNonQuery(sqldefault);
                LoadData(this.dateStart.Text, this.dateEnd.Text);
                MessageBox.Show("操作成功");
                return;
            }
            if (string.IsNullOrEmpty(Id) || !Regex.IsMatch(Id, @"^\d+$"))
                return;
            AddSheet addForm = new AddSheet(LoginUser, PatientInfo, Id);
            addForm.ShowDialog();
            if (addForm.DialogResult != DialogResult.OK) return;
            LoadData("", "");
        }
        #endregion

        #region 解决dev GridControl刷新数据后，滚动条恢复原来位置
        int topIndex = -1;
        private void bandedGridView1_TopRowChanged(object sender, EventArgs e)
        {
            topIndex = bandedGridView1.TopRowIndex;
        }
        #endregion

        #region 12 24小时右击事件
        private void ToolStripMenuItem12_Click(object sender, EventArgs e)
        {
            SumData(12, "07:01");
        }

        private void SumData(int hours, string beiginTime)
        {
            int[] select = bandedGridView1.GetSelectedRows();
            if (select.Length == 0) return;
            int num = bandedGridView1.GetSelectedRows()[0];
            string RiQi = bandedGridView1.GetRowCellValue(num, "riqi").ToString();
            int formId = (int)FormType.NurseForm;
            string formName = EnumHelper.GetDescription(FormType.NurseForm);
            switch (hours)
            {
                case 12:
                    string sql12 = @"if(EXISTS (SELECT Id FROM NursingFormSumIO(NOLOCK) WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}' ))
                            BEGIN UPDATE NursingFormSumIO SET Group12 ='Y' WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}' END ELSE BEGIN
                            INSERT INTO NursingFormSumIO (PatientId,VisitId,SumDate,PatientName,BedNo,DepartmentId,DepartmentName,AreaId,AreaName,FormId,FormName,Group12,Group24,GroupDiy,BeginTime)
                            VALUES('{0}','{1}','{2}' ,'{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','Y',NULL,NULL,'{11}') END";
                    sql12 = string.Format(sql12, PatientInfo.PATIENT_ID, PatientInfo.VISIT_ID, Convert.ToDateTime(RiQi).ToString("yyyy-MM-dd"), PatientInfo.PATIENT_NAME, PatientInfo.BED_NO, PatientInfo.DEPARTMENT_ID, PatientInfo.DEPARTMENT_NAME, PatientInfo.NURSE_CELL_CODE, PatientInfo.NURSE_CELL_NAME, formId, formName, beiginTime);
                    SqlHelper.ExecuteNonQuery(CommandType.Text, sql12);
                    break;
                case 24:
                    string sql24 = @"if(EXISTS (SELECT Id FROM NursingFormSumIO(NOLOCK) WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}' ))
                            BEGIN UPDATE NursingFormSumIO SET Group24 ='Y' WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}' END ELSE BEGIN
                            INSERT INTO NursingFormSumIO (PatientId,VisitId,SumDate,PatientName,BedNo,DepartmentId,DepartmentName,AreaId,AreaName,FormId,FormName,Group12,Group24,GroupDiy,BeginTime)
                            VALUES('{0}','{1}','{2}' ,'{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}',NULL,'Y',NULL,'{11}') END";
                    sql24 = string.Format(sql24, PatientInfo.PATIENT_ID, PatientInfo.VISIT_ID, Convert.ToDateTime(RiQi).ToString("yyyy-MM-dd"), PatientInfo.PATIENT_NAME, PatientInfo.BED_NO, PatientInfo.DEPARTMENT_ID, PatientInfo.DEPARTMENT_NAME, PatientInfo.NURSE_CELL_CODE, PatientInfo.NURSE_CELL_NAME, formId, formName, beiginTime);
                    SqlHelper.ExecuteNonQuery(CommandType.Text, sql24);
                    break;
                default:
                    string sqldefault = @"if(EXISTS (SELECT Id FROM NursingFormSumIO(NOLOCK) WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}'  ))
                            BEGIN UPDATE NursingFormSumIO SET GroupDiy ='{12}',BeginTime='{11}' WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}'  END ELSE BEGIN
                            INSERT INTO NursingFormSumIO (PatientId,VisitId,SumDate,PatientName,BedNo,DepartmentId,DepartmentName,AreaId,AreaName,FormId,FormName,Group12,Group24,BeginTime,GroupDiy)
                            VALUES('{0}','{1}','{2}' ,'{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}',NULL,NULL,'{11}','{12}') END";
                    sqldefault = string.Format(sqldefault, PatientInfo.PATIENT_ID, PatientInfo.VISIT_ID, Convert.ToDateTime(RiQi).ToString("yyyy-MM-dd"), PatientInfo.PATIENT_NAME, PatientInfo.BED_NO, PatientInfo.DEPARTMENT_ID, PatientInfo.DEPARTMENT_NAME, PatientInfo.NURSE_CELL_CODE, PatientInfo.NURSE_CELL_NAME, formId, formName, beiginTime, hours);
                    SqlHelper.ExecuteNonQuery(sqldefault);
                    break;
            }
            MessageBox.Show("操作成功");
            string StatDate = this.dateStart.Text;
            string EndDate = this.dateEnd.Text;

            if (string.IsNullOrEmpty(StatDate) || string.IsNullOrEmpty(EndDate))
            {
                MessageBox.Show("查询日期不能为空！");
            }
            LoadData(StatDate, EndDate);
        }
        #endregion

        #region 删除统计时间
        private void ToolStripMenuItem24_Click(object sender, EventArgs e)
        {
            SumData(24, "07:01");
        }
        private void ToolStripMenuItemdelete12_Click(object sender, EventArgs e)
        {
            DeleteSumData(12);
        }
        private void ToolStripMenuItemdelete24_Click(object sender, EventArgs e)
        {
            DeleteSumData(24);
        }
        private void DeleteSumData(int hours)
        {
            if (bandedGridView1.RowCount <= 0) return;
            string RiQi = bandedGridView1.GetRowCellValue(bandedGridView1.FocusedRowHandle, "riqi").ToString();
            string SumDate = Convert.ToDateTime(RiQi).ToString("yyyy-MM-dd");
            string id = bandedGridView1.GetRowCellValue(bandedGridView1.FocusedRowHandle, "Id").ToString();
            if (!string.IsNullOrEmpty(id) && id.IndexOf("-") > 0 && id.Split('-').Length == 3)
                SumDate = Convert.ToDateTime(id).ToString("yyyy-MM-dd");

            int formId = (int)FormType.NurseForm;
            string formName = EnumHelper.GetDescription(FormType.NurseForm);
            switch (hours)
            {
                case 12:
                    UpdateNursingFormSumIO(12, PatientInfo.PATIENT_ID, PatientInfo.VISIT_ID, SumDate, (int)FormType.NurseForm, PatientInfo.NURSE_CELL_CODE);
                    break;
                case 24:
                    UpdateNursingFormSumIO(24, PatientInfo.PATIENT_ID, PatientInfo.VISIT_ID, SumDate, (int)FormType.NurseForm, PatientInfo.NURSE_CELL_CODE);
                    break;
                default:
                    string sqldef = @"SELECT TOP 1 GroupDiy FROM NursingFormSumIO(NOLOCK) WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}'  ";
                    sqldef = string.Format(sqldef, PatientInfo.PATIENT_ID, PatientInfo.VISIT_ID, RiQi, this.PatientInfo.PATIENT_NAME, this.PatientInfo.BED_NO, PatientInfo.DEPARTMENT_ID, PatientInfo.DEPARTMENT_NAME, PatientInfo.NURSE_CELL_CODE, PatientInfo.NURSE_CELL_NAME, formId, formName);
                    object obj = SqlHelper.ExecuteScalar(sqldef);
                    if (obj != DBNull.Value && obj != null && obj.ToString().Length > 0)
                    {
                        string sqldef_update = @" UPDATE NursingFormSumIO SET GroupDiy=NULL,BeginTime='07:01' WHERE PatientId = '{0}' AND VisitId = '{1}' AND SumDate = '{2}' AND FormId='{9}' AND AreaId='{7}' ";
                        sqldef_update = string.Format(sqldef_update, PatientInfo.PATIENT_ID, PatientInfo.VISIT_ID, RiQi, PatientInfo.PATIENT_NAME, PatientInfo.BED_NO, PatientInfo.DEPARTMENT_ID, PatientInfo.DEPARTMENT_NAME, PatientInfo.NURSE_CELL_CODE, PatientInfo.NURSE_CELL_NAME, formId, formName);
                        SqlHelper.ExecuteNonQuery(CommandType.Text, sqldef_update);
                        MessageBox.Show("操作成功");
                    }
                    else
                    {
                        MessageBox.Show("当日未添加统计行");
                    }
                    break;
            }
            string StatDate = this.dateStart.Text;
            string EndDate = this.dateEnd.Text;

            if (string.IsNullOrEmpty(StatDate) || string.IsNullOrEmpty(EndDate))
            {
                MessageBox.Show("查询日期不能为空！");
            }
            LoadData(StatDate, EndDate);
        }
        private void UpdateNursingFormSumIO(int type, string PatientId, int VisitId, string SumDate, int FormId, string AreaId)
        {
            string select = string.Format("SELECT Id,Group12,Group24 FROM NursingFormSumIO(NOLOCK) WHERE PatientId = '{0}' AND VisitId = {1} AND SumDate = '{2}' AND FormId={3} AND AreaId='{4}'", PatientId, VisitId, SumDate, FormId, AreaId);
            DataTable dt = (SqlHelper.ExecuteDataset(select, CommandType.Text)).Tables[0];
            if ((dt.Rows.Count > 0) && (dt.Rows[0]["Group" + type].ToString().Contains("Y")))
            {
                string update = string.Format("UPDATE NursingFormSumIO SET Group{0} ='' WHERE PatientId = '{1}' AND VisitId = {2} AND SumDate = '{3}' AND FormId={4} AND AreaId='{5}'", type, PatientId, VisitId, SumDate, FormId, AreaId);
                SqlHelper.ExecuteNonQuery(CommandType.Text, update);
                MessageBox.Show("操作成功");
            }
            else
            {
                MessageBox.Show("当日未添加统计行");
            }
        }
        #endregion

        private void ToolStripMenuItemAddContiPrint_Click(object sender, EventArgs e)
        {
            continueflag = true;//续打标识
            int[] select = bandedGridView1.GetSelectedRows();
            if (select.Length == 0) return;
            continuenum = bandedGridView1.GetSelectedRows()[0];//倒序的行数
            MessageBox.Show("添加续打成功");
        }

        private void ToolStripMenuItemDiy_Click(object sender, EventArgs e)
        {
            int[] select = bandedGridView1.GetSelectedRows();
            if (select.Length == 0) return;
            int num = bandedGridView1.GetSelectedRows()[0];
            string date = bandedGridView1.GetRowCellValue(num, "riqi").ToString();
            string etime = bandedGridView1.GetRowCellValue(num, "shijian").ToString();
            string stime = "07:01";
            NursingSummaryHours frm = new NursingSummaryHours(date, stime, etime);
            frm.ShowDialog();
            if (frm.DialogResult != System.Windows.Forms.DialogResult.OK) return;
            //return data:
            date = frm.Date;
            stime = frm.Stime;
            etime = frm.Etime;

            TimeSpan _etime = DateTime.Parse(etime).TimeOfDay;
            TimeSpan _stime = DateTime.Parse(stime).TimeOfDay;
            int hours = (_etime.Hours - _stime.Hours);
            if (hours >= 0) hours += 1;
            if (hours < 0) hours = 24 + hours + 1;
            SumData(hours, stime);
        }

        private void ToolStripMenuItemDiyDel_Click(object sender, EventArgs e)
        {
            DeleteSumData(0);
        }
    }
}
public class RegexHelper
{
    public static bool IsFloat(object val)
    {
        if (val == DBNull.Value) return false;
        if (val == null) return false;
        if (string.IsNullOrEmpty(val.ToString())) return false;
        if (!Regex.IsMatch(val.ToString(), @"^(0|([1-9]\d*))(\.\d+)?$")) return false;
        float result;
        if (!Single.TryParse(val.ToString(), out result)) return false;
        return true;
    }
    public static bool IsDouble(object val)
    {
        if (val == DBNull.Value) return false;
        if (val == null) return false;
        if (string.IsNullOrEmpty(val.ToString())) return false;
        if (!Regex.IsMatch(val.ToString(), @"^(0|([1-9]\d*))(\.\d+)?$")) return false;
        double result;
        if (!Double.TryParse(val.ToString(), out result)) return false;
        return true;
    }
    public static bool IsInt32(object val)
    {
        if (val == DBNull.Value) return false;
        if (val == null) return false;
        if (string.IsNullOrEmpty(val.ToString())) return false;
        if (!Regex.IsMatch(val.ToString(), @"^\d+$")) return false;
        int result;
        if (!Int32.TryParse(val.ToString(), out result)) return false;
        return true;
    }
}